#include "xmlfilehelper.h"

XmlFileHelper::XmlFileHelper(QString path, QObject *parent)
    :QObject (parent)
{
    this->path = path;
}

XmlFileHelper::~XmlFileHelper()
{

}



QDomDocument XmlFileHelper::OpenXmlFile(QString root_name)
{
    // 打开或者创建一个XML文件
    QDomNode  root;
    QFile file(path);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    // 创建 XML DOM 文档
    QDomDocument doc;
    if (file.size() == 0) {
        // 文件为空，创建根节点
        QDomProcessingInstruction instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
        doc.appendChild(instruction);
        root = doc.createElement(root_name);
        doc.appendChild(root);
        QTextStream stream(&file);
        doc.save(stream, 4);		// 缩进四格
    } else {
        // 文件不为空，读取 XML 内容
        if (!doc.setContent(&file)) {
            qDebug() << "无法读取 XML 文件" + path;
            file.close();
            return doc;
        }
    }
    file.close();
    return doc;
}

QDomNode XmlFileHelper::FindChildNode(QDomNode node, const QString& nodeName) {
    if (node.isElement() && node.nodeName() == nodeName) {
        return node;
    }

    QDomNode child = node.firstChild();
    while (!child.isNull()) {
        QDomNode foundNode = FindChildNode(child, nodeName);
        if (!foundNode.isNull()) {
            return foundNode;
        }
        child = child.nextSibling();
    }
    return QDomNode();
}


